#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试爬虫程序
"""

import requests
import json
from datetime import datetime, timedelta

def test_api_connection():
    """测试API连接"""
    print("开始测试API连接...")
    
    # 使用您提供的curl命令参数
    url = "https://www.hnsggzy.com/tradeApi/constructionTender/ListConstructionTenderPlan"
    
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Referer": "https://www.hnsggzy.com/",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
        "sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"'
    }
    
    cookies = {
        "JSESSIONID": "e24a7a43-c642-4726-901b-ab09dac5b1e6",
        "SESSION": "ZTI0YTdhNDMtYzY0Mi00NzI2LTkwMWItYWIwOWRhYzViMWU2"
    }
    
    # 测试不同的参数组合
    test_cases = [
        {
            "name": "原始参数（未来日期）",
            "params": {
                "current": 3,
                "size": 10,
                "noticeSendTimeStart": "2025-09-25 00:00:00",
                "noticeSendTimeEnd": "2025-09-26 23:59:59",
                "descs": "noticeSendDate"
            }
        },
        {
            "name": "当前日期范围",
            "params": {
                "current": 1,
                "size": 10,
                "noticeSendTimeStart": "2024-12-01 00:00:00",
                "noticeSendTimeEnd": "2024-12-31 23:59:59",
                "descs": "noticeSendDate"
            }
        },
        {
            "name": "无日期限制",
            "params": {
                "current": 1,
                "size": 10,
                "descs": "noticeSendDate"
            }
        }
    ]
    
    for test_case in test_cases:
        print(f"\n测试: {test_case['name']}")
        print(f"参数: {test_case['params']}")
        
        try:
            response = requests.get(url, headers=headers, cookies=cookies, 
                                  params=test_case['params'], timeout=30)
            
            print(f"状态码: {response.status_code}")
            print(f"响应头: {dict(response.headers)}")
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    print(f"响应数据: {json.dumps(data, ensure_ascii=False, indent=2)[:500]}...")
                    
                    if 'records' in data:
                        print(f"✓ 成功获取数据，共 {len(data['records'])} 条记录")
                        if data['records']:
                            print(f"第一条记录ID: {data['records'][0].get('id', 'N/A')}")
                    else:
                        print("✗ 响应中没有records字段")
                        
                except json.JSONDecodeError as e:
                    print(f"✗ JSON解析失败: {e}")
                    print(f"响应内容: {response.text[:500]}")
            else:
                print(f"✗ HTTP错误: {response.status_code}")
                print(f"响应内容: {response.text[:500]}")
                
        except requests.exceptions.RequestException as e:
            print(f"✗ 请求失败: {e}")
        
        print("-" * 50)

def test_detail_api():
    """测试详情API"""
    print("\n测试详情API...")
    
    url = "https://www.hnsggzy.com/tradeApi/constructionTender/getConstructionTenderPlanById"
    
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Referer": "https://www.hnsggzy.com/",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
        "sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"'
    }
    
    cookies = {
        "JSESSIONID": "e24a7a43-c642-4726-901b-ab09dac5b1e6",
        "SESSION": "ZTI0YTdhNDMtYzY0Mi00NzI2LTkwMWItYWIwOWRhYzViMWU2"
    }
    
    # 使用您提供的ID
    test_id = "95906179-79c7-47d4-b4e8-cbb64cbe94c4"
    params = {"id": test_id}
    
    try:
        response = requests.get(url, headers=headers, cookies=cookies, 
                              params=params, timeout=30)
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            try:
                data = response.json()
                print(f"✓ 详情API测试成功")
                print(f"响应数据: {json.dumps(data, ensure_ascii=False, indent=2)[:500]}...")
            except json.JSONDecodeError as e:
                print(f"✗ JSON解析失败: {e}")
                print(f"响应内容: {response.text[:500]}")
        else:
            print(f"✗ HTTP错误: {response.status_code}")
            print(f"响应内容: {response.text[:500]}")
            
    except requests.exceptions.RequestException as e:
        print(f"✗ 请求失败: {e}")

if __name__ == "__main__":
    test_api_connection()
    test_detail_api()
